#include <limits>
#include <iostream>

#include <assimp/postprocess.h>
#include <assimp/version.h>
#include <assimp/scene.h>
#include <assimp/Importer.hpp>
#include <assimp/Exporter.hpp>
#include <assimp/DefaultLogger.hpp>

#include "common/assimp.h"


std::size_t get_matching_format(
    std::string const& outf,
    Assimp::Exporter const& exporter)
{
  for (size_t i = 0, end = exporter.GetExportFormatCount();
       i < end; ++i)
  {
    const aiExportFormatDesc* const e = exporter.GetExportFormatDescription(i);
    if (outf == e->id) return i;
  }

  return std::numeric_limits<std::size_t>::max();
}


std::string get_import_extensions(void)
{
  std::string result;
  Assimp::Importer imp;
  imp.GetExtensionList(result);
  return result;
}


bool translate_mesh(std::string const& input, std::string const& output)
{
  std::string outext,outbase;

  Assimp::Importer importer;
  Assimp::Exporter exporter;

  std::string::size_type const s = output.find_last_of('.');
  if (s != std::string::npos)
  {
    outext  = output.substr(s+1);
    outbase = output.substr(0,s);
  }

  std::size_t outfi = get_matching_format(outext, exporter);

  // Set the export format descriptor.
  aiExportFormatDesc const* const e =  exporter.GetExportFormatDescription(outfi);
  std::cout
      << "assimp export: select file format: \'"
      << e->id
      << "\' "
      << e->description
      << std::endl;

  // Import the  model.
  const aiScene* scene = importer.ReadFile(input, aiProcess_Triangulate);
  if (!scene) return false;

  // Call the export routine.
  if (exporter.Export(scene, e->id, output) != AI_SUCCESS) return false;

  std::cout
      << "assimp export: wrote output file: "
      << output
      << std::endl;

  return true;
}


bool translate_mesh_for_preview(
    std::string const& input, std::string const& output)
{
  return translate_mesh(input, output);
}
